# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations

#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################
from BeautifulSoup import BeautifulSoup
from gluon.html import web2pyHTMLParser
import urllib
import string
import re
import datetime

def index():
    """
    example action using the internationalization operator T and flash
    rendered by views/default/index.html or views/generic.html
    """
    response.flash = "Welcome to web2py!"
    session.referurl=URL(args=request.args,vars=request.vars)
    return dict(message=T("Welcome to Zengjie's system"))

def addProduct():
    session.backurl=session.referurl
    form = crud.create(db.Product,message='Add new product successfully',
            next='show/product/[id]')
    session.referurl=URL(args=request.args,vars=request.vars)
    return dict(form=form)

def addOrder():
    session.backurl=session.referurl
    session.referurl=URL(args=request.args,vars=request.vars)
    form = crud.create(db.OrderRecord,message='Add new order successfully',
            next='show/order/[id]')
    return dict(form=form)

def addDetailImage():
    id=request.args[0]
    image = db(db.DetailImage.Product==id).select().first()
    #form = crud.create(db.DetailImage,message='Add detail image successfully', next='show/product/[id]')

    form = SQLFORM(db.DetailImage)
    if form.process().accepted:
        response.flash = 'form accepted'

    return dict(form=form,productid=id)

#show only one product
def show():

    type=request.args[0]
    id=request.args[1]
    if type=='product':
        form = crud.read(db.Product, id)
        addButton=A(T("Add Detail Image"), _href=URL('addDetailImage', args=id), _class='button',_style='margin-top: 1em;')
        additionInfo=GetAdditionInfoDetailImage(id)

    elif type=='order':

        form = crud.read(db.OrderRecord, id)
        addButton=A(T("Add Relationship"), _href=URL('addOrderProductRelation', args=id), _class='button',_style='margin-top: 1em;')
        additionInfo=GetAdditionInfoOrder(id)


    button=A(T("Edit"), _href=URL('edit/%s'%type, args=id), _class='button',_style='margin-top: 1em;')
    return dict(form=form,id=id,editButton=button, addButton=addButton,info=additionInfo)

def GetAdditionInfoDetailImage(productId):
    imageList = db(db.DetailImage.Product == productId).select()
    table=TABLE()
    for image in imageList:
        row=TR(TD(IMG(_src=URL('download',args=image.image))))
        table.append(row)

    form = crud.create(db.DetailImage,message='Add detail image successfully')

    span=SPAN(DIV(table),DIV(form))

    return span

def GetAdditionInfoOrder(orderId):
    session.backurl=session.referurl
    session.referurl=URL(args=request.args,vars=request.vars)

    productListInOrder = db(db.relation_order_product.OrderRecord == orderId).select()
    table=TABLE(TR(TD('ID'),TD("Thumbnail"),TD("Brand"),TD("Name"),TD("Current Price"),TD("Reference Price"),TD("SalePrice")))
    for item in productListInOrder:
        row=TR(TD(A(item.Product.id,_href=URL('show/product',args=item.Product.id))),
                TD(A(IMG(_src=URL('download', args=item.Product.thumbnail), _class='thumbnail'),_href=URL('show/product',args=item.Product.id))),
                TD(item.Product.brand),
                TD(item.Product.name),
                TD(item.Product.currentPrice),
                TD(item.Product.recordPrice),
                TD(A(item.Product.taobaoPrice, _class='taobaoPrice',_href=URL(item.Product.taobaoLink)))
               )
        table.append(row)


    return table


#edit only one product
def edit():
    session.backurl=session.referurl
    session.referurl=URL(args=request.args,vars=request.vars)
    type=request.args[0]
    id=request.args[1]

    if type=='product':
        form = crud.update(db.Product, id, next='show/product/[id]')
    elif type=='order':
        form = crud.update(db.OrderRecord, id, next='show/order/[id]')
    return dict(form=form,id=1)

#show all the product
def showAll():
    session.backurl=session.referurl
    session.referurl=URL(args=request.args,vars=request.vars)
    fields=[db.Product.id,db.Product.brand,db.Product.name,db.Product.type,db.Product.gender,db.Product.currentPrice,db.Product.recordPrice,db.Product.taobaoPrice]
    grid = SQLFORM.smartgrid(db.Product,fields=fields)
    return dict(grid=grid)

def addOrderProductRelation():
    session.backurl=session.referurl
    session.referurl=URL(args=request.args,vars=request.vars)
    grid = SQLFORM.smartgrid(db.relation_order_product)
    return dict(grid=grid)

def showWarn():
    session.backurl=session.referurl
    session.referurl=URL(args=request.args,vars=request.vars)
    table=TABLE(TR(TD('ID'),TD("Thumbnail"),TD("Brand"),TD("Name"),TD("Current Price"),TD("Reference Price"),TD("SalePrice")))

    productList = db().select(db.Product.ALL)
    for product in productList:
        if (product.currentPrice > product.recordPrice) or product.currentPrice =='0':
            row=TR(TD(A(product.id,_href=URL('show/product',args=product.id))),
                TD(A(IMG(_src=URL('download', args=product.thumbnail), _class='thumbnail'),_href=URL('show/product',args=product.id))),
                TD(product.brand),
                TD(product.name),
                TD(product.currentPrice),
                TD(product.recordPrice),
                TD(A(product.taobaoPrice, _class='taobaoPrice',_href=URL(product.taobaoLink)))
               )
            row['_class']="WARN"

            table.append(row)

    return dict(table=table)

def showTest():
    #session.backurl=session.referurl
    #session.referurl=URL(args=request.args,vars=request.vars)
    grid = SQLFORM.smartgrid(db.relation_order_product)

    #u=session.referurl
    u=updatePrice(13)
    return dict(grid=grid,u=u)

#show selected product
brandList = db().select(db.Product.ALL,distinct=True)
genderList = db().select(db.Product.ALL,distinct=True)
typeList = db().select(db.Product.ALL,distinct=True)

blist = set([row['brand'] for row in brandList])
brandoptions = [OPTION(name) for name in blist]

glist = set([row['gender'] for row in genderList])
genderoptions = [OPTION(gender) for gender in glist]

tlist = set([row['type'] for row in typeList])
typeoptions = [OPTION(type) for type in tlist]

def showSelected():
    session.backurl=session.referurl
    session.referurl=URL(args=request.args,vars=request.vars)
    fpList=[]
    form = FORM(SELECT(OPTION("Select Brand",_value=-1),*brandoptions,_name='brand'),
                SELECT(OPTION("Select Gender",_value=-1),*genderoptions,_name='gender'),
                SELECT(OPTION("Select Type",_value=-1),*typeoptions,_name='type'),
                SELECT(OPTION('Sort By',_value=-1),'Name','Price','Brand','Discount',_name='sort'),
                INPUT(_type='submit'))
    if form.process().accepted:
        response.flash = 'Show Selected Product'  
        brand=request.vars.brand
        gender=request.vars.gender      
        type=request.vars.type      
        sort = request.vars.sort

        if sort == 'Name':
            fpList=db().select(db.Product.ALL, orderby=db.Product.name)
        elif sort == 'Brand':
            fpList=db().select(db.Product.ALL, orderby=db.Product.brand)
        elif sort == 'Price':
            fpList=db().select(db.Product.ALL, orderby=db.Product.recordPrice)
        elif sort == '-1':
            fpList=db().select(db.Product.ALL)

        if brand != '-1':
            fpList=fpList.find(lambda row: row.brand==brand)
        if gender != '-1':
            fpList=fpList.find(lambda row: row.gender==gender)
        if type != '-1':
            fpList=fpList.find(lambda row: row.type==type)

    return dict(productList=fpList,form=form)


def updatePrice(id):
    session.backurl=session.referurl
    session.referurl=URL(args=request.args,vars=request.vars)
    #return true means the price value changed, return false means no change
    product = db(db.Product.id==id).select().first()

    path = "%s" % product.src_link
    try:
        #f = open(path)
        f = urllib.urlopen(product.src_link)
    except:
        return
    data = f.read()
    f.close()

    soup = BeautifulSoup(data)
    try:
        l = soup.find('span', attrs={'id':"price"})

        if l==None:
            price="$0"
        else:
            price = l.contents[0]
    except:
        price = "$0"

    try:
        priceValue=re.match(r".*\$(.*)", price).groups()[0]
    except:
        try:
            priceValue=re.match(r"\n.*\$(.*)\n", price).groups()[0]
        except:
            priceValue=0


    if product.currentPrice != priceValue:
        product.currentPrice = priceValue
        product.update_record()

        db.PriceRecord.insert(Product=product,price=priceValue,update_on=datetime.datetime.now())

        return True

    return False

def updateAll():
    session.backurl=session.referurl
    session.referurl=URL(args=request.args,vars=request.vars)
    table=TABLE(TR(TD('ID'),TD("Thumbnail"),TD("Brand"),TD("Name"),TD("Current Price"),TD("Reference Price"),TD("SalePrice")))

    productList = db().select(db.Product.ALL)
    for product in productList:
        isChanged = updatePrice(product.id)
        row=TR(TD(A(product.id,_href=URL('show/product',args=product.id))),
                TD(A(IMG(_src=URL('download', args=product.thumbnail), _class='thumbnail'),_href=URL('show/product',args=product.id))),
                TD(product.brand),
                TD(product.name),
                TD(product.currentPrice),
                TD(product.recordPrice),
                TD(A(product.taobaoPrice, _class='taobaoPrice',_href=URL(product.taobaoLink)))
               )

        if isChanged:
            #the price value changed
            row['_class']="INFO"
            if product.currentPrice > product.recordPrice:
                row['_class']="WARN"
        else:
            row['_class']="NORMAL"

            if product.currentPrice > product.recordPrice:
                row['_class']="WARN"

        if product.currentPrice == '0':
            row['_class']="FATA"

        table.append(row)


    return dict(table=table)

#show all the order
def showOrderRelation():
    session.backurl=session.referurl
    session.referurl=URL(args=request.args,vars=request.vars)
    table = SQLFORM.smartgrid(db.OrderRecord)

    order_and_product = db((db.OrderRecord.id == db.relation_order_product.OrderRecord))
    return dict(table=table)

def showOrder():
    table=TABLE(TR(TD('ID'),TD("Number"),TD("Order on"),TD("Order at"),TD("Total Price"),TD("Discount"),TD("Actual Price")))

    orderList = db().select(db.OrderRecord.ALL)
    for order in orderList:
        row=TR(TD(A(order.id,_href=URL('show/order',args=order.id))),
                TD(A(order.number,_href=URL('show/order',args=order.id))),
                TD(order.order_on),
                TD(order.order_at),
                TD(order.total_price),
                TD(order.discount),
                TD(order.actual_price)
                )

        table.append(row)

    return dict(table=table)

def user():
    """
    exposes:
    http://..../[app]/default/user/login
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    return dict(form=auth())


def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)


def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    return service()


@auth.requires_signature()
def data():
    """
    http://..../[app]/default/data/tables
    http://..../[app]/default/data/create/[table]
    http://..../[app]/default/data/read/[table]/[id]
    http://..../[app]/default/data/update/[table]/[id]
    http://..../[app]/default/data/delete/[table]/[id]
    http://..../[app]/default/data/select/[table]
    http://..../[app]/default/data/search/[table]
    but URLs must be signed, i.e. linked with
      A('table',_href=URL('data/tables',user_signature=True))
    or with the signed load operator
      LOAD('default','data.load',args='tables',ajax=True,user_signature=True)
    """
    return dict(form=crud())

